package com.durian.ui.span;

/**
 * 说明：VerticalImageSpan
 * <p>
 * 作者：fanly
 * <p>
 * 类型：Class
 * <p>
 * 时间：2016/8/24 19:22
 * <p>
 * 版本：version 1.0
 */

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

/**
 * 垂直居中的ImageSpan
 *
 * @author KenChung
 */
public class VerticalImageSpan extends ImageSpan {

    private float sx,sy;

    public VerticalImageSpan(Context context, int resourceId,float sx,float sy) {
        super(context, resourceId);
        this.sx = sx;
        this.sy = sy;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {
        Drawable b = getDrawable();
        Paint.FontMetricsInt fm = paint.getFontMetricsInt();
        int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;//计算y方向的位移
        canvas.save();
        canvas.translate(x, transY);//绘制图片位移一段距离
        canvas.scale(sx,sy);
        b.draw(canvas);
        canvas.restore();
    }

    @Override
    public Drawable getDrawable() {
        Drawable drawable = super.getDrawable();
        if (sx != 1 || sy != 1){
            Rect srcRect = drawable.getBounds();
            Rect targetRect = new Rect(0,0,(int) (srcRect.right * sx),(int) (srcRect.bottom * sy));
            drawable.setBounds(targetRect);
        }
        return drawable;
    }
}

